package com.hqq.concurrency.double_checked_locking;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Inventory
 * Created by heqianqian on 2017/7/31.
 */
public class Inventory {

    private static final Logger LOGGER = LoggerFactory.getLogger(Inventory.class);

    private List<Item> itemList;

    private int inventorySize;

    private Lock lock;

    public Inventory(int inventorySize) {
        this.inventorySize = inventorySize;
        this.itemList = new ArrayList<>();
        this.lock = new ReentrantLock();
    }

    /**
     * 添加Item
     */
    public boolean addItem(Item item) {
        if (itemList.size() < inventorySize) {
            lock.lock();
            try {
                if (itemList.size() < inventorySize) {
                    itemList.add(item);
                    LOGGER.info("{}:  items.size()={}, inventorySize={}", Thread.currentThread().getName(), itemList.size(), inventorySize);
                    return true;
                }
            } finally {
                lock.unlock();
            }
        }
        return false;
    }

    public List<Item> getItemList() {
        return Collections.unmodifiableList(itemList);
    }

}
